const express = require("express");
const router = express.Router();
const { student, teacher } = require("../../models/User");
const bcrypt = require("bcrypt");
const gravatar = require("gravatar");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
const passport = require("passport");
const { json } = require("body-parser");


// get请求,请求地址: api/users/test access：public
router.get("/test", (req, res) => {
    res.json({ msg: "404" });
});

// 学生注册
router.post('/student', (req, res) => {
    const { name, college, className, password, student_number } = req.body
    new student({
        name,
        college,
        className,
        password: password ? password : 123456,
        student_number
    }).save(() => {
        res.status(200).json({
            code: 200,
            msg: '添加成功'
        })
    })
})

// 老师注册
router.post('/teacher', (req, res) => {
    const { name, password } = req.body
    new teacher({
        name,
        password: password ? password : 123456
    }).save().then(() => {
        res.status(200).json({
            code: 200,
            msg: '添加成功'
        })
    })
})

// 注册
router.post("/register", (req, res) => {
    const identity = req.body.identity,
        avatar = gravatar.url('1679525084@qq.com', { s: "200", r: "pg", d: "mm" })
    let user = null

    if (identity === 'student') {
        // 注册人是学生
        user = new student({
            name: req.body.name,
            password: req.body.password,
            avatar,
            teacherId: req.body.teacherId,
            identity
        })
    } else {
        // 注册人是老师
        user = new teacher({
            name: req.body.name,
            password: req.body.password,
            avatar,
            identity
        })
    }

    user.save().then(() => res.json({
        status: 200,
        msg: `欢迎你，${req.body.name}${identity === 'student' ? '同学' : '老师'}`
    })).catch(error => {
        console.log(error);
        res.send(500)
    })
});

// 后台登录
router.post("/login", (req, res) => {

    // 查询数据库
    // const studentData = new Promise((resolve, reject) => student.findOne({ name: req.body.name }).then(res => resolve(res)).catch(err => reject(err))),
    const teacherData = new Promise((resolve, reject) => teacher.findOne({ name: req.body.name }).then(res => resolve(res)).catch(err => reject(err)))

    Promise.all([teacherData]).then(result => {
        if (!result[0] && !result[1]) return res.json({
            status: 404,
            msg: '用户不存在'
        })

        res.json({
            status: 200,
            msg: '登录成功',
            data: {
                id: result[0]._id,
                name: result[0].name,
                avatar: result[0].avatar
            }
        })
    })


    // console.log(studentData, teacherData);
    // if (!studentData && !teacherData) return res.json({
    //   status: 404,
    //   msg: '用户不存在'
    // })
    // res.json({
    //   status: 200,
    //   msg: '登录成功',
    //   data: studentData ? studentData : teacherData
    // })

    // const student = await 

    // User.findOne({ email }).then(user => {
    //   if (!user) {
    //     return res.json({
    //       status: 201,
    //       data: "用户不存在"
    //     });
    //   } else {
    //     // 密码匹配
    //     bcrypt.compare(password, user.password).then(isMatch => {
    //       if (isMatch) {
    //         const rule = { id: user.id, name: user.name };
    //         // jwt.sign("规则","加密名字","过期时间","箭头函数")
    //         jwt.sign(rule, keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
    //           if (err) throw err;
    //           res.json({
    //             status: 200,
    //             token: "Bearer " + token
    //           });
    //         });
    //       } else {
    //         return res.json({
    //           status: 201,
    //           data: "密码错误"
    //         })
    //       }
    //     });
    //   }
    // });
});

// 根据id查询老师
router.get("/teacher/:id", (req, res) => {
    teacher.findOne({ _id: req.params.id }).then(result => {
        res.json({
            status: 200,
            msg: '获取成功',
            data: {
                id: result._id,
                name: result.name,
                avatar: result.avatar
            }
        })
    })
})

// 获取老师列表
router.get("/list/teacher", async(req, res) => {
    let { current, size } = req.query
    current = current ? current : 1
    size = size ? size : 5
    const total = await (new Promise((resolve, reject) => teacher.find().then(data => resolve(data.length))))
    teacher.find().skip((current - 1) * size).limit(Number(size)).then(result => {
        res.status(200).json({
            code: 200,
            data: {
                size,
                total,
                pages: Math.ceil(total / size),
                current,
                records: result.map(({ _id, name, avatar, identity, createdDate }) => {
                    return {
                        id: _id,
                        name,
                        avatar,
                        identity,
                        createdDate
                    }
                })
            }
        })
    })
})

// 修改老师信息
router.put("/teacher", (req, res) => {
    let $set = {}
    const { id, name, password } = req.body
    if (password && name) {
        $set = {
            name,
            password
        }
    } else if (name) {
        $set = { name }
    } else if (password) {
        $set = { password }
    }
    teacher.findOneAndUpdate({ _id: id }, { $set }, { new: true }).then(result => {
        res.status(200).json({
            code: 200,
            msg: '修改成功'
        })
    }).catch(error => {
        res.status(500).json({
            code: 500,
            msg: '修改失败'
        })
    })
})

// 删除老师
router.delete('/teacher', (req, res) =>
    teacher.findByIdAndRemove({ _id: req.body.id }).then(result => {
        res.status(200).json({
            code: 200,
            msg: '删除成功'
        })
    }).catch(error => {
        res.status(500).json({
            code: 500,
            msg: '删除失败'
        })
    })
)

// 删除学生
router.delete('/student', (req, res) => {
    student.findOneAndRemove({ _id: req.body.id }).then(result => {
        res.json({
            code: 200,
            msg: '删除成功'
        })
    })
})

// 获取学生列表
router.get('/list/student', async(req, res) => {
    const { search } = req.query
    let { current, size } = req.query,
        searchData = {}
    if (search) {
        searchData = {
            $or: [{ name: { $regex: search } }]
        }
    }

    console.log(searchData.name);
    current = current ? current : 1
    size = size ? size : 5
    const total = await (new Promise((resolve, reject) => student.find(searchData).then(data => resolve(data.length))))
    student.find(searchData).skip((current - 1) * size).limit(Number(size)).then(result => {
        res.status(200).json({
            code: 200,
            data: {
                size,
                total,
                pages: Math.ceil(total / size),
                current,
                records: result.map(({ _id, name, avatar, college, createdDate, student_number, className }) => {
                    return {
                        id: _id,
                        name,
                        avatar,
                        college,
                        className,
                        createdDate,
                        student_number,
                    }
                })
            }
        })
    })
})

// 修改学生信息
router.put('/student', (req, res) => {
    const { id, name, college, className, student_number } = req.body
    const _id = id,
        $set = {
            name: name ? name : '',
            className: className ? className : '',
            college: college ? college : '',
            student_number: student_number ? student_number : ''
        }
    student.findOneAndUpdate({ _id }, { $set }, { new: true }).then(result => {
        res.status(200).json({
            code: 200,
            msg: '修改成功'
        })
    }).catch(error => {
        res.status(500).json({
            code: 500,
            msg: '修改失败'
        })
    })
})


module.exports = router;